const app = getApp();
const util = require('../../utils/util.js')
Page({
    data: {
        imageUrl: app.globalData.imageUrl,
        curpage: 0,
        secondkill_list: [],
        hasmore: true,
        cart_count: 0,
        goodsImageFly: "",
        show_fly_img: false,
        cartGoods: {},
        scrollTop: 0
    },
    onLoad: function() {
        //请求分享数据
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=wx_share&op=get_share',
            data: {},
            method: 'GET',
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    this.setData({
                        share_default_title: res.data.datas.title,
                        share_default_image_url: res.data.datas.imageUrl
                    })
                }
            }
        })
    },
    onShow: function() {
        if (this.data.hasmore) {
            this.getData()
        }
        wx.getStorage({
            key: 'cart_count',
            success: (res) => {
                this.setData({
                    cart_count: res.data,
                })
            }
        });
        wx.getStorage({
            key: 'key',
            success: (res) => {
                this.setData({
                    key: res.data,
                })
                this.getCartInfo();
            }
        });
        this.cartPos = {};
        this.cartPos['x'] = 30;
        this.cartPos['y'] = app.globalData.sh - 50;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    getData: function() {
        let self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=promotion&op=secondkill',
            method: 'GET',
            data: {
                curpage: self.data.curpage + 1
            },
            success: res => {
                if (res.data.code == 200) {
                    self.setData({
                        secondkill_list: self.data.secondkill_list.concat(res.data.datas.secondkill_list),
                        hasmore: res.data.hasmore,
                        curpage: self.data.curpage + 1
                    })

                    if (res.data.hasmore && res.data.datas.secondkill_list[0].goods_list.length <= 5) {
                        wx.request({
                            url: app.globalData.ApiUrl + '/index.php?act=promotion&op=secondkill',
                            method: 'GET',
                            data: {
                                curpage: self.data.curpage + 1
                            },
                            success: res => {
                                if (res.data.code == 200) {
                                    self.setData({
                                        secondkill_list: self.data.secondkill_list.concat(res.data.datas.secondkill_list),
                                        hasmore: res.data.hasmore,
                                        curpage: self.data.curpage + 1
                                    })
                                }
                            }
                        })

                    }
                }
            }
        })
    },
    getCartInfo: function() {
        var self = this;
        wx.request({
            url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_list',
            data: {
                key: self.data.key
            },
            method: 'POST',
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            dataType: 'json',
            success: res => {
                if (res.data.code == '200') {
                    self.setData({
                        cart_list: res.data.datas.cart_list
                    })
                    var selfGoods = {};
                    var arrtemp = new Array();
                    for (let i = 0; i < 20; i++) {
                        arrtemp[i] = new Object();
                    }
                    for (let i = 0; i < self.data.cart_list.length; i++) {
                        for (let j = 0; j < self.data.cart_list[i].goods.length; j++) {
                            selfGoods[self.data.cart_list[i].goods[j].goods_id] = {
                                cart_id: self.data.cart_list[i].goods[j].cart_id,
                                goods_num: self.data.cart_list[i].goods[j].goods_num
                            }
                        }
                    }
                    self.setData({
                        cartGoods: selfGoods
                    })
                }
            }
        })
    },
    addCart: function(e) {
        let self = this;
        let goods_id = e.currentTarget.dataset['goods_id'];
        let quantity = 1;
        let addQuantity = 0;
        let goods_img = e.currentTarget.dataset['goods_img'];
        if (this.data.cartGoods[goods_id]) {
            addQuantity = this.data.cartGoods[goods_id].goods_num * 1 + 1;
        } else {
            addQuantity = 1
        }
        this.setData({
            goodsImageFly: goods_img
        })
        wx.getStorage({
            key: 'key',
            success: (res) => {
                wx.request({
                    url: app.globalData.ApiUrl + '/index.php?act=member_cart&op=cart_add_edit',
                    data: {
                        key: res.data,
                        goods_id: goods_id,
                        quantity: addQuantity
                    },
                    method: 'POST',
                    header: {
                        'content-type': 'application/x-www-form-urlencoded'
                    },
                    dataType: 'json',
                    success: (res) => {
                        if (res.data.code == 200) {
                            wx.getStorage({
                                key: 'cart_count',
                                success: (res) => {
                                    wx.setStorage({
                                        key: 'cart_count',
                                        data: res.data + quantity
                                    })
                                },
                            })
                            self.addcartAnimation(e);
                            self.setData({
                                cart_count: self.data.cart_count + 1
                            })
                            if (this.data.cartGoods[goods_id]) {
                                self.data.cartGoods[goods_id].goods_num++;
                                self.setData({
                                    cartGoods: self.data.cartGoods
                                })
                            } else {
                                self.data.cartGoods[goods_id] = {
                                    cart_id: res.data.datas,
                                    goods_num: 1
                                }
                                self.setData({
                                    cartGoods: self.data.cartGoods
                                })
                            }

                        } else {
                            wx.showToast({
                                title: res.data.datas.error,
                                icon: 'none'
                            })
                        }
                    }
                });
            },
            fail: () => {
                if (app.globalData.authorized) {
                    wx.navigateTo({
                        url: "../chooselogin/chooselogin"
                    })
                } else {
                    wx.navigateTo({
                        url: "../login/login"
                    })
                }
            }
        })
    },
    /**
     * 页面滚动事件的处理函数
     */
    onPageScroll: function(e) {
        this.setData({
            scrollTop: e.scrollTop
        })
    },
    goTop: function(e) { // 一键回到顶部
        if (wx.pageScrollTo) {
            wx.pageScrollTo({
                scrollTop: 0
            })
        } else {
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    goToCart: function() {
        wx.getStorage({
            key: 'key',
            success: (res) => {
                wx.switchTab({
                    url: "../cart/cart"
                })
            },
            fail: () => {
                if (app.globalData.authorized) {
                    wx.navigateTo({
                        url: "../chooselogin/chooselogin"
                    })
                } else {
                    wx.navigateTo({
                        url: "../login/login"
                    })
                }
            }
        })
    },
    addcartAnimation: function(e) {
        if (this.data.show_fly_img)
            return;
        this.finger = {};
        var topPoint = {};
        this.finger['x'] = e.touches["0"].clientX - 100;
        this.finger['y'] = e.touches["0"].clientY - 30;
        if (this.finger['x'] - this.cartPos['x'] < 0) {
            topPoint['x'] = (this.cartPos['x'] - this.finger['x']) / 2 + this.finger['x'];
        } else {
            topPoint['x'] = Math.abs(this.cartPos['x'] - this.finger['x']) / 2 + this.cartPos['x'];
        }
        if (this.finger['y'] < this.cartPos['y']) {
            topPoint['y'] = this.finger['y'] - 80;
        } else {
            topPoint['y'] = this.cartPos['y'] - 80;
        }
        this.linePos = app.bezier([this.finger, topPoint, this.cartPos], 20);
        this.startAnimation();
    },
    startAnimation: function() {
        var index = 0,
            self = this,
            bezier_points = this.linePos['bezier_points'];
        this.setData({
            show_fly_img: true,
            fly_x: self.finger['x'],
            fly_y: self.finger['y']
        })
        this.timer = setInterval(() => {
            self.setData({
                fly_x: bezier_points[index]['x'],
                fly_y: bezier_points[index]['y']
            })
            index++;
            if (index >= 20) {
                clearInterval(self.timer);
                self.setData({
                    show_fly_img: false
                })
            }
        }, 16);
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        if (this.data.hasmore) {
            this.getData()
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        let share_key = this.data.key ? this.data.key : '';
        let share_path = '';
        if (util.getCurrentPageUrlWithArgs().indexOf("?") != -1) {
            share_path = util.getCurrentPageUrlWithArgs() + '&share_key=' + share_key;
        } else {
            share_path = util.getCurrentPageUrlWithArgs() + '?share_key=' + share_key;
        }
        return {
            title: this.data.share_default_title,
            imageUrl: this.data.share_default_image_url,
            path: share_path
        }
    }
})